package routes

import (
	"encoding/json"
	"fmt"
	modbus "github.com/thinkgos/gomodbus/v2"
	"io"
	"net/http"
)

type ReadPLC struct {
	Value int64 `json:"value"`
}

func registerPLCRoutes() {
	http.HandleFunc("/api/getPLC", handlegetPLC)
}

func handlegetPLC(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		w.Header().Set("Access-Control-Allow-Origin", "*")
		var plc ReadPLC
		p := modbus.NewTCPClientProvider("192.168.0.20:3003", modbus.WithEnableLogger())
		client := modbus.NewClient(p)
		err := client.Connect()
		if err != nil {
			fmt.Println("connect failed, ", err)
			return
		}
		defer client.Close()
		results, err := client.ReadHoldingRegisters(1, 0, 48)
		if err != nil {
			fmt.Println(err.Error() + "---------------------------")
		}
		plc.Value = int64(results[15])
		b, _ := json.Marshal(plc)
		io.WriteString(w, string(b))
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}
